import json
import math
import sqlite3

import requests
from flask import Flask, render_template, request, redirect, url_for, session, flash, jsonify
from werkzeug.security import generate_password_hash, check_password_hash
import datetime

app = Flask(__name__)
app.secret_key = 'your_secret_key'  # 请修改为足够复杂的密钥
DATABASE = 'it_assets.db'


def get_db_connection():
    conn = sqlite3.connect(DATABASE)
    conn.row_factory = sqlite3.Row
    return conn

# 获取主机属性设置（用于动态生成字段）
def get_host_properties():
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM host_properties")
    rows = cursor.fetchall()
    conn.close()
    return [dict(r) for r in rows]

# 辅助函数：获取中间件属性设置
def get_middleware_properties():
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM middleware_properties")
    rows = cursor.fetchall()
    conn.close()
    return [dict(row) for row in rows]

# 在 init_db() 中增加创建中间件属性表的代码
def init_db():
    conn = get_db_connection()
    cursor = conn.cursor()
    # 用户表
    cursor.execute('''
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                username TEXT UNIQUE NOT NULL,
                password TEXT NOT NULL
            )
        ''')
    # 主机属性表（由管理员在“主机属性设置”中配置）
    cursor.execute('''
            CREATE TABLE IF NOT EXISTS host_properties (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                type TEXT NOT NULL,
                required INTEGER NOT NULL DEFAULT 0,
                unique_attr INTEGER NOT NULL DEFAULT 0,
                placeholder TEXT
            )
        ''')
    # 中间件属性表（略，此处已有）
    cursor.execute('''
            CREATE TABLE IF NOT EXISTS middleware_properties (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                type TEXT NOT NULL,
                required INTEGER NOT NULL DEFAULT 0,
                unique_attr INTEGER NOT NULL DEFAULT 0,
                placeholder TEXT
            )
        ''')
    # 主机表：存储主机记录，字段动态，由 host_properties 定义，记录存储为 JSON 字符串
    cursor.execute('''
            CREATE TABLE IF NOT EXISTS hosts (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                data TEXT NOT NULL
            )
        ''')

    # 创建中间件记录表，数据以 JSON 形式存储
    cursor.execute('''
            CREATE TABLE IF NOT EXISTS middlewares (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                data TEXT NOT NULL
            )
        ''')
    # 插入默认管理员账号
    cursor.execute("SELECT * FROM users WHERE username = ?", ("admin",))
    if cursor.fetchone() is None:
        from werkzeug.security import generate_password_hash
        hashed_password = generate_password_hash("admin123")
        cursor.execute("INSERT INTO users (username, password) VALUES (?, ?)", ("admin", hashed_password))
    conn.commit()
    conn.close()


@app.route('/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM users WHERE username = ?", (username,))
        user = cursor.fetchone()
        conn.close()
        if user and check_password_hash(user['password'], password):
            session['user_id'] = user['id']
            session['username'] = user['username']
            return redirect(url_for('home'))
        else:
            flash('用户名或密码错误！')
    return render_template('login.html')


@app.route('/home')
def home():
    # 获取主机数量
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT COUNT(*) as count FROM hosts")
    host_row = cursor.fetchone()
    host_total = host_row['count'] if host_row else 0

    host_properties = get_host_properties()  # 从 host_properties 表获取所有主机属性
    middleware_properties = get_middleware_properties()  # 从 middleware_properties 表获取所有中间件属性

    host_columns = host_properties[:3]  # 取前两个属性作为展示列
    middleware_columns = middleware_properties[:3]

    # 获取中间件数量
    cursor.execute("SELECT COUNT(*) as count FROM middlewares")
    middleware_row = cursor.fetchone()
    middleware_total = middleware_row['count'] if middleware_row else 0

    # 获取最近新增主机记录（假设按 id 降序排序，取前 5 条）
    cursor.execute("SELECT * FROM hosts ORDER BY id DESC LIMIT 5")
    host_rows = cursor.fetchall()
    recent_hosts = []
    for row in host_rows:
        try:
            data = json.loads(row['data'])
        except Exception:
            data = {}
        data['id'] = row['id']
        recent_hosts.append(data)

    # 获取最近新增中间件记录
    cursor.execute("SELECT * FROM middlewares ORDER BY id DESC LIMIT 5")
    middleware_rows = cursor.fetchall()
    recent_middlewares = []
    for row in middleware_rows:
        try:
            data = json.loads(row['data'])
        except Exception:
            data = {}
        data['id'] = row['id']
        recent_middlewares.append(data)
    conn.close()

    # 示例天气数据
    weather = "晴 25°C"

    return render_template("home.html",
                           host_total=host_total,
                           middleware_total=middleware_total,
                           weather=weather,
                           recent_hosts=recent_hosts,
                           recent_middlewares=recent_middlewares,
                           host_columns=host_columns,
                           middleware_columns=middleware_columns)


# Weatherbit API Key（替换为你自己的 API Key）
API_KEY = 'YOUR_WEATHERBIT_API_KEY'
BASE_URL = 'https://api.weatherbit.io/v2.0/current'


@app.route('/get_weather', methods=['GET'])
def get_weather():
    # 获取前端传递的纬度和经度
    lat = request.args.get('lat')
    lon = request.args.get('lon')

    if not lat or not lon:
        return jsonify({"error": "Invalid latitude or longitude"}), 400

    try:
        # 构建请求的 URL
        url = f'{BASE_URL}?lat={lat}&lon={lon}&key={API_KEY}'
        response = requests.get(url)
        response.raise_for_status()  # 如果响应不是 200，抛出异常

        data = response.json()

        # 获取天气数据
        weather = data['data'][0]
        temp = weather['temp']
        desc = weather['weather']['description']
        icon_code = weather['weather']['icon']  # 获取天气图标代码

        # 构建图标 URL
        icon_url = f"https://www.weatherbit.io/static/img/icons/{icon_code}.png"

        return jsonify({
            'temperature': temp,
            'description': desc,
            'icon': icon_url
        })

    except requests.exceptions.RequestException as e:
        # 捕获请求异常
        return jsonify({"error": str(e)}), 500
    except Exception as e:
        # 捕获其他异常
        return jsonify({"error": f"Internal Server Error: {str(e)}"}), 500


@app.route('/change_password', methods=['GET', 'POST'])
def change_password():
    if 'user_id' not in session:
        return redirect(url_for('login'))
    if request.method == 'POST':
        original_password = request.form['original_password']
        new_password = request.form['new_password']
        confirm_new_password = request.form['confirm_new_password']
        if new_password != confirm_new_password:
            flash("新密码和确认密码不一致！")
            return redirect(url_for('change_password'))
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM users WHERE id = ?", (session['user_id'],))
        user = cursor.fetchone()
        if user and check_password_hash(user['password'], original_password):
            hashed_new_password = generate_password_hash(new_password)
            cursor.execute("UPDATE users SET password = ? WHERE id = ?", (hashed_new_password, session['user_id']))
            conn.commit()
            conn.close()
            flash("密码修改成功！")
            return redirect(url_for('home'))
        else:
            flash("原密码错误！")
            conn.close()
            return redirect(url_for('change_password'))
    return render_template('change_password.html')


@app.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('login'))


# 1. 属性列表
@app.route('/host_attributes')
def host_attributes():
    if 'user_id' not in session:
        return redirect(url_for('login'))
    conn = get_db_connection()
    cursor = conn.cursor()
    # 查询 host_properties 表中的所有记录
    properties = cursor.execute("SELECT * FROM host_properties").fetchall()
    conn.close()
    # 如果查询结果为 None，则置为空列表
    if properties is None:
        properties = []
    # 为确保所有记录都是标准字典，如果使用了 sqlite3.Row，可转换如下：
    properties = [dict(row) for row in properties]
    return render_template('host_attributes.html', properties=properties)


# 2. 添加属性（POST）
@app.route('/host_attributes/add', methods=['POST'])
def add_host_property():
    # 获取表单数据，并执行插入操作……
    try:
        # 插入数据示例：
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute(
            "INSERT INTO host_properties (name, type, required, unique_attr, placeholder) VALUES (?, ?, ?, ?, ?)",
            (request.form.get("name").strip(),
             request.form.get("type").strip(),
             1 if request.form.get("required") == "1" else 0,
             1 if request.form.get("unique_attr") == "1" else 0,
             request.form.get("placeholder", "").strip())
        )
        conn.commit()
        conn.close()
        return jsonify({'success': True, 'message': '添加成功'})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)})


@app.route('/host_attributes/update/<int:prop_id>', methods=['POST'])
def update_host_attribute(prop_id):
    # 从 request.form 中获取数据
    name = request.form.get("name", "").strip()
    prop_type = request.form.get("type", "").strip()
    required = 1 if request.form.get("required") == "1" else 0
    unique_attr = 1 if request.form.get("unique_attr") == "1" else 0
    placeholder = request.form.get("placeholder", "").strip()

    if not name or not prop_type:
        return jsonify({'success': False, 'message': '属性名称和类型为必填'})

    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        # 更新 host_properties 表记录的示例 SQL
        cursor.execute(
            "UPDATE host_properties SET name=?, type=?, required=?, unique_attr=?, placeholder=? WHERE id=?",
            (name, prop_type, required, unique_attr, placeholder, prop_id)
        )
        conn.commit()
    except Exception as e:
        return jsonify({'success': False, 'message': '更新失败：' + str(e)})
    finally:
        conn.close()

    return jsonify({'success': True, 'message': '更新成功'})


# 3. 单条删除属性（POST）
@app.route('/host_attributes/delete/<int:prop_id>', methods=['POST'])
def delete_host_attribute(prop_id):
    if 'user_id' not in session:
        return jsonify({'success': False, 'message': '未登录'})
    conn = get_db_connection()
    try:
        conn.execute("DELETE FROM host_properties WHERE id = ?", (prop_id,))
        conn.commit()
    except Exception as e:
        conn.close()
        return jsonify({'success': False, 'message': '删除失败: ' + str(e)})
    conn.close()
    return jsonify({'success': True, 'message': '删除成功'})

# 4. 批量删除属性（POST）
@app.route('/host_attributes/delete_batch', methods=['POST'])
def delete_host_attributes_batch():
    if 'user_id' not in session:
        return jsonify({'success': False, 'message': '未登录'})
    ids_str = request.form.get('ids', '')
    if not ids_str:
        return jsonify({'success': False, 'message': '未指定删除记录'})
    try:
        ids = [int(x) for x in ids_str.split(',') if x.strip()]
    except Exception:
        return jsonify({'success': False, 'message': '无效的ID'})

    conn = get_db_connection()
    cursor = conn.cursor()
    try:
        for id_val in ids:
            cursor.execute("DELETE FROM host_properties WHERE id = ?", (id_val,))
        conn.commit()
    except Exception as e:
        conn.close()
        return jsonify({'success': False, 'message': '批量删除失败: ' + str(e)})
    conn.close()
    return jsonify({'success': True, 'message': '删除成功'})


# 获取中间件属性列表
@app.route('/middleware_attributes')
def middleware_attributes():
    if 'user_id' not in session:
        return redirect(url_for('login'))
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM middleware_properties")
    properties = cursor.fetchall()
    conn.close()
    # 将查询结果转换为字典列表，调试输出
    middleware_properties = [dict(row) for row in properties]
    # print("查询到中间件属性:", middleware_properties)
    return render_template('middleware_attributes.html', middleware_properties=middleware_properties)


# 处理添加中间件属性的 AJAX 请求
@app.route('/middleware_attributes/add', methods=['POST'])
def add_middleware_attribute():
    name = request.form.get("name", "").strip()
    type_ = request.form.get("type", "").strip()
    required = 1 if request.form.get("required") == "1" else 0
    unique_attr = 1 if request.form.get("unique_attr") == "1" else 0
    placeholder = request.form.get("placeholder", "").strip()

    if not name or not type_:
        return jsonify({'success': False, 'message': '属性名称和类型为必填项'})

    # 检查属性名称唯一性
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT COUNT(*) as count FROM middleware_properties WHERE LOWER(name)=LOWER(?)", (name,))
        row = cursor.fetchone()
        if row["count"] > 0:
            conn.close()
            return jsonify({'success': False, 'message': '属性名称已存在'})
        # 插入新属性记录
        cursor.execute(
            "INSERT INTO middleware_properties (name, type, required, unique_attr, placeholder) VALUES (?, ?, ?, ?, ?)",
            (name, type_, required, unique_attr, placeholder)
        )
        conn.commit()
        conn.close()
        return jsonify({'success': True, 'message': '添加成功'})
    except Exception as e:
        return jsonify({'success': False, 'message': '添加失败：' + str(e)})


# 更新中间件属性
@app.route('/middleware_attributes/update/<int:prop_id>', methods=['POST'])
def update_middleware_attribute(prop_id):
    name = request.form.get("name", "").strip()
    type_ = request.form.get("type", "").strip()
    required = 1 if request.form.get("required") == "1" else 0
    unique_attr = 1 if request.form.get("unique_attr") == "1" else 0
    placeholder = request.form.get("placeholder", "").strip()

    if not name or not type_:
        return jsonify({'success': False, 'message': '属性名称和类型为必填项'})

    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        # 如果有需要，可以在更新时检查属性名称唯一性（排除当前记录）
        cursor.execute("SELECT COUNT(*) as count FROM middleware_properties WHERE LOWER(name)=LOWER(?) AND id != ?",
                       (name, prop_id))
        row = cursor.fetchone()
        if row["count"] > 0:
            conn.close()
            return jsonify({'success': False, 'message': '属性名称已存在'})
        cursor.execute(
            "UPDATE middleware_properties SET name = ?, type = ?, required = ?, unique_attr = ?, placeholder = ? WHERE id = ?",
            (name, type_, required, unique_attr, placeholder, prop_id)
        )
        conn.commit()
        conn.close()
        return jsonify({'success': True, 'message': '更新成功'})
    except Exception as e:
        return jsonify({'success': False, 'message': '更新失败：' + str(e)})
# 处理删除中间件属性的 AJAX 请求
@app.route('/middleware_attributes/delete/<int:prop_id>', methods=['POST'])
def delete_middleware_attribute(prop_id):
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("DELETE FROM middleware_properties WHERE id = ?", (prop_id,))
        conn.commit()
        conn.close()
        return jsonify({'success': True, 'message': '删除成功'})
    except Exception as e:
        return jsonify({'success': False, 'message': '删除失败：' + str(e)})

# ------------------------
# 主机管理相关路由
# ------------------------

# 显示主机管理页面，主机列表的字段由 host_properties 决定
# ------------------------- 主机管理功能 -------------------------

# 列表展示主机，支持分页和搜索，动态字段来自 host_properties 表
@app.route('/hosts')
def hosts():
    if 'user_id' not in session:
        return redirect(url_for('login'))

    q = request.args.get('q', '').strip()
    try:
        page = int(request.args.get('page', 1))
    except ValueError:
        page = 1
    try:
        per_page = int(request.args.get('per_page', 10))
    except ValueError:
        per_page = 10
    offset = (page - 1) * per_page

    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT COUNT(*) as count FROM hosts")
    total_row = cursor.fetchone()
    total = total_row['count'] if total_row else 0
    cursor.execute("SELECT * FROM hosts LIMIT ? OFFSET ?", (per_page, offset))
    rows = cursor.fetchall()
    conn.close()

    host_list = []
    for row in rows:
        try:
            data = json.loads(row['data'])
        except Exception:
            data = {}
        data['id'] = row['id']
        host_list.append(data)

    # 若传入搜索关键字则在 Python 端模糊过滤
    if q:
        filtered = []
        for host in host_list:
            for key, value in host.items():
                if key == 'id':
                    continue
                if isinstance(value, str) and q.lower() in value.lower():
                    filtered.append(host)
                    break
                elif q.lower() in str(value).lower():
                    filtered.append(host)
                    break
        host_list = filtered
        total = len(filtered)
    total_pages = math.ceil(total / per_page) if per_page > 0 else 1

    # 查询动态字段（主机属性设置），例如在 host_properties 表中
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM host_properties")
    props_rows = cursor.fetchall()
    conn.close()
    properties = [dict(r) for r in props_rows]
    print("properties:", properties)

    return render_template("hosts.html", hosts=host_list, properties=properties, q=q, page=page, per_page=per_page,
                           total=total, total_pages=total_pages)

# 添加主机记录接口（AJAX 提交）
@app.route('/host/add', methods=['POST'])
def add_host():
    if 'user_id' not in session:
        return redirect(url_for('login'))

    properties = get_host_properties()
    host_data = {}
    for prop in properties:
        field_name = prop['name']
        host_data[field_name] = request.form.get(field_name, "").strip()

    # 唯一性检查：遍历所有设置唯一的字段，并检查数据库中是否已经存在相同的值
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT id, data FROM hosts")
    existing_rows = cursor.fetchall()
    conn.close()

    for prop in properties:
        if prop.get("unique_attr"):
            field_name = prop["name"]
            new_value = host_data.get(field_name, "")
            if new_value:
                for row in existing_rows:
                    try:
                        record = json.loads(row["data"])
                    except Exception:
                        continue
                    if record.get(field_name, "") == new_value:
                        return jsonify(
                            {'success': False, 'message': f"字段 {field_name} 值 '{new_value}' 已存在，请填写唯一的值"})

    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("INSERT INTO hosts (data) VALUES (?)", (json.dumps(host_data),))
        conn.commit()
        conn.close()
        return jsonify({'success': True, 'message': '添加成功'})
    except Exception as e:
        return jsonify({'success': False, 'message': '添加失败：' + str(e)})


# 单条删除主机记录接口
@app.route('/host/delete_single/<int:host_id>', methods=['POST'])
def delete_host_single(host_id):
    if 'user_id' not in session:
        return redirect(url_for('login'))
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("DELETE FROM hosts WHERE id = ?", (host_id,))
        conn.commit()
        conn.close()
        return jsonify({'success': True, 'message': '删除成功'})
    except Exception as e:
        return jsonify({'success': False, 'message': '删除失败：' + str(e)})

# 批量删除主机记录接口（接收 host id 列表，逗号分隔）
@app.route('/host/delete_batch', methods=['POST'])
def delete_host_batch():
    if 'user_id' not in session:
        return redirect(url_for('login'))
    ids_str = request.form.get("ids", "")
    if not ids_str:
        return jsonify({'success': False, 'message': '未提供删除ID'})
    try:
        ids = [int(x) for x in ids_str.split(',')]
        conn = get_db_connection()
        cursor = conn.cursor()
        query = "DELETE FROM hosts WHERE id IN ({})".format(",".join("?" * len(ids)))
        cursor.execute(query, ids)
        conn.commit()
        conn.close()
        return jsonify({'success': True, 'message': '批量删除成功'})
    except Exception as e:
        return jsonify({'success': False, 'message': '批量删除失败：' + str(e)})


@app.route('/host/update/<int:host_id>', methods=['POST'])
def update_host(host_id):
    if 'user_id' not in session:
        return redirect(url_for('login'))

    properties = get_host_properties()
    host_data = {}
    for prop in properties:
        field_name = prop['name']
        host_data[field_name] = request.form.get(field_name, "").strip()

    # 唯一性检查：排除当前记录
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT id, data FROM hosts WHERE id != ?", (host_id,))
    other_rows = cursor.fetchall()
    conn.close()

    for prop in properties:
        if prop.get("unique_attr"):
            field_name = prop["name"]
            new_value = host_data.get(field_name, "")
            if new_value:
                for row in other_rows:
                    try:
                        record = json.loads(row["data"])
                    except Exception:
                        continue
                    if record.get(field_name, "") == new_value:
                        return jsonify(
                            {'success': False, 'message': f"字段 {field_name} 值 '{new_value}' 已存在，请填写唯一的值"})

    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("UPDATE hosts SET data = ? WHERE id = ?", (json.dumps(host_data), host_id))
        conn.commit()
        conn.close()
        return jsonify({'success': True, 'message': '更新成功'})
    except Exception as e:
        return jsonify({'success': False, 'message': '更新失败：' + str(e)})


# 1. 中间件列表（分页、搜索）
@app.route('/middlewares')
def middlewares():
    if 'user_id' not in session:
        return redirect(url_for('login'))

    q = request.args.get('q', '').strip()
    try:
        page = int(request.args.get('page', 1))
    except ValueError:
        page = 1
    try:
        per_page = int(request.args.get('per_page', 10))
    except ValueError:
        per_page = 10
    offset = (page - 1) * per_page

    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT COUNT(*) as count FROM middlewares")
    total_row = cursor.fetchone()
    total = total_row['count'] if total_row else 0

    cursor.execute("SELECT * FROM middlewares LIMIT ? OFFSET ?", (per_page, offset))
    rows = cursor.fetchall()
    conn.close()

    middleware_list = []
    for row in rows:
        try:
            data = json.loads(row['data'])
        except Exception:
            data = {}
        data['id'] = row['id']
        middleware_list.append(data)

    # 如果有搜索关键词 q，则简单模糊过滤所有记录
    if q:
        filtered = []
        for m in middleware_list:
            for key, value in m.items():
                if key == 'id':
                    continue
                if isinstance(value, str) and q.lower() in value.lower():
                    filtered.append(m)
                    break
                elif q.lower() in str(value).lower():
                    filtered.append(m)
                    break
        middleware_list = filtered
        total = len(filtered)
    total_pages = math.ceil(total / per_page) if per_page > 0 else 1

    properties = get_middleware_properties()

    return render_template("middleware.html",
                           middlewares=middleware_list,
                           middleware_properties=properties,
                           q=q, page=page, per_page=per_page,
                           total=total, total_pages=total_pages)


# 2. 添加中间件记录
@app.route('/middleware/add', methods=['POST'])
def add_middleware():
    if 'user_id' not in session:
        return redirect(url_for('login'))

    properties = get_middleware_properties()
    middleware_data = {}
    for prop in properties:
        field_name = prop['name']
        middleware_data[field_name] = request.form.get(field_name, "").strip()

    # 唯一性检查：对于每个设置了唯一的字段，查找数据库中是否已存在相同的值
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT id, data FROM middlewares")
    existing_rows = cursor.fetchall()
    conn.close()

    for prop in properties:
        if prop.get("unique_attr"):
            field_name = prop["name"]
            new_value = middleware_data.get(field_name, "")
            if new_value:
                for row in existing_rows:
                    try:
                        record = json.loads(row["data"])
                    except Exception:
                        continue
                    if record.get(field_name, "") == new_value:
                        return jsonify({'success': False,
                                        'message': f"字段 {field_name} 值 '{new_value}' 已存在，请填写唯一的值"})

    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("INSERT INTO middlewares (data) VALUES (?)", (json.dumps(middleware_data),))
        conn.commit()
        conn.close()
        return jsonify({'success': True, 'message': '添加成功'})
    except Exception as e:
        return jsonify({'success': False, 'message': '添加失败：' + str(e)})


# 3. 修改中间件记录
@app.route('/middleware/update/<int:middleware_id>', methods=['POST'])
def update_middleware(middleware_id):
    if 'user_id' not in session:
        return redirect(url_for('login'))

    properties = get_middleware_properties()
    middleware_data = {}
    for prop in properties:
        field_name = prop['name']
        middleware_data[field_name] = request.form.get(field_name, "").strip()

    # 唯一性检查：排除当前记录
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT id, data FROM middlewares WHERE id != ?", (middleware_id,))
    other_rows = cursor.fetchall()
    conn.close()

    for prop in properties:
        if prop.get("unique_attr"):
            field_name = prop["name"]
            new_value = middleware_data.get(field_name, "")
            if new_value:
                for row in other_rows:
                    try:
                        record = json.loads(row["data"])
                    except Exception:
                        continue
                    if record.get(field_name, "") == new_value:
                        return jsonify({'success': False,
                                        'message': f"字段 {field_name} 值 '{new_value}' 已存在，请填写唯一的值"})

    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("UPDATE middlewares SET data = ? WHERE id = ?", (json.dumps(middleware_data), middleware_id))
        conn.commit()
        conn.close()
        return jsonify({'success': True, 'message': '更新成功'})
    except Exception as e:
        return jsonify({'success': False, 'message': '更新失败：' + str(e)})


# 4. 单条删除中间件记录
@app.route('/middleware/delete_single/<int:middleware_id>', methods=['POST'])
def delete_middleware_single(middleware_id):
    if 'user_id' not in session:
        return redirect(url_for('login'))
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("DELETE FROM middlewares WHERE id = ?", (middleware_id,))
        conn.commit()
        conn.close()
        return jsonify({'success': True, 'message': '删除成功'})
    except Exception as e:
        return jsonify({'success': False, 'message': '删除失败：' + str(e)})


# 5. 批量删除中间件记录
@app.route('/middleware/delete_batch', methods=['POST'])
def delete_middleware_batch():
    if 'user_id' not in session:
        return redirect(url_for('login'))
    ids_str = request.form.get("ids", "")
    if not ids_str:
        return jsonify({'success': False, 'message': '未提供删除ID'})
    try:
        ids = [int(x) for x in ids_str.split(',')]
        conn = get_db_connection()
        cursor = conn.cursor()
        query = "DELETE FROM middlewares WHERE id IN (" + ",".join("?" * len(ids)) + ")"
        cursor.execute(query, ids)
        conn.commit()
        conn.close()
        return jsonify({'success': True, 'message': '批量删除成功'})
    except Exception as e:
        return jsonify({'success': False, 'message': '批量删除失败：' + str(e)})


if __name__ == '__main__':
    init_db()
    app.run(debug=True, port=5000, host='0.0.0.0')
